package com.example.sunmiv1.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.LossInfoAdapter;
import com.example.sunmiv1.adapter.ReportLossManageAdapter;
import com.example.sunmiv1.entity.LossInfo;
import com.example.sunmiv1.entity.ReportLossListInfo;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;
import static com.example.sunmiv1.utils.Tools.getDateFromDatePickerDialog;

public class ReportLossManageActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.startTime_rlManage)
    TextView startTimeRlManage;
    @BindView(R.id.endTime_rlManage)
    TextView endTimeRlManage;
    @BindView(R.id.tvSearch_rlManage)
    TextView tvSearchRlManage;
    @BindView(R.id.edit_rlManage)
    EditText editRlManage;
    @BindView(R.id.iv_rlManage)
    ImageView ivRlManage;
    @BindView(R.id.add_rlManage)
    Button addRlManage;
    @BindView(R.id.listView_rlManage)
    PullToRefreshListView listViewRlManage;
    @BindView(R.id.close_reportLossList)
    ImageView closeReportLossList;
    @BindView(R.id.detailLv_reportLossList)
    ListView detailLvReportLossList;
    @BindView(R.id.ll_reportLossList)
    LinearLayout llReportLossList;
    @BindView(R.id.rl_reportLossList)
    LinearLayout rlReportLossList;

    private Context context;
    private ACache aCache;
    private ReportLossListInfo reportLossListInfo;
    private List<ReportLossListInfo.DataBean> list = new ArrayList<>();
    private LoadingDialog loadingDialog;
    private int page = 1;
    private ReportLossManageAdapter reportLossManageAdapter;
    private Intent intent;

    private LossInfo lossInfo;
    private List<LossInfo.DataBean> lossList = new ArrayList<>();
    private LossInfoAdapter lossInfoAdapter;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    for (ReportLossListInfo.DataBean dataBean : reportLossListInfo.getData()) {
                        list.add(dataBean);
                    }
                    page++;
                    setReportLossManageAdapter();
                    break;
                case 2:
                    setReportLossManageAdapter();
                    break;
                case 3:
                    lossList.clear();
                    for (LossInfo.DataBean dataBean : lossInfo.getData()) {
                        lossList.add(dataBean);
                    }
                    setLossInfoAdapter();
                    rlReportLossList.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    setLossInfoAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_report_loss_manage);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.reportLossManageTitle);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        initListener();
    }

    private void initListener() {
        listViewRlManage.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
                setReportLossManageAdapter();
                getData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getData();
            }
        });
    }

    @OnClick({R.id.title_back, R.id.startTime_rlManage, R.id.endTime_rlManage, R.id.tvSearch_rlManage, R.id.iv_rlManage,
            R.id.add_rlManage, R.id.close_reportLossList, R.id.ll_reportLossList, R.id.rl_reportLossList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.startTime_rlManage:
                getDateFromDatePickerDialog(startTimeRlManage);
                break;
            case R.id.endTime_rlManage:
                getDateFromDatePickerDialog(endTimeRlManage);
                break;
            case R.id.tvSearch_rlManage:
                page = 1;
                list.clear();
                setReportLossManageAdapter();
                getData();
                break;
            case R.id.iv_rlManage:
                page = 1;
                list.clear();
                setReportLossManageAdapter();
                getData();
                break;
            case R.id.add_rlManage://新增報損單
                intent = new Intent(context, NewReportLossActivity.class);
                startActivity(intent);
                break;
            case R.id.close_reportLossList:
                rlReportLossList.setVisibility(View.GONE);
                break;
            case R.id.ll_reportLossList:
                break;
            case R.id.rl_reportLossList:
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        list.clear();
        setReportLossManageAdapter();
        getData();
    }


    /**
     * 報損列表適配器
     */
    private void setReportLossManageAdapter() {
        if (reportLossManageAdapter == null) {
            reportLossManageAdapter = new ReportLossManageAdapter(context, list);
            listViewRlManage.setAdapter(reportLossManageAdapter);
        } else {
            reportLossManageAdapter.notifyDataSetChanged();
        }
        reportLossManageAdapter.Click(index -> {
            getDetail(list.get(index).getId());
        });
    }

    private void setLossInfoAdapter() {
        if (lossInfoAdapter == null) {
            lossInfoAdapter = new LossInfoAdapter(lossList, context);
            detailLvReportLossList.setAdapter(lossInfoAdapter);
        } else {
            lossInfoAdapter.notifyDataSetChanged();
        }
        lossInfoAdapter.setChoose(index -> {
            if ("1".equals(lossList.get(index).getSerial_number_state())) {
                rlReportLossList.setVisibility(View.GONE);
                Intent intent = new Intent(context, StringCodeOperationActivity.class);
                intent.putExtra("operation", 25);
                intent.putExtra("id",lossList.get(index).getId());
                context.startActivity(intent);
            }
        });
    }

    /**
     * 獲取報損列表
     */
    private void getData() {
        loadingDialog.show();
        String url = "";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            if ("2".equals(aCache.getAsString("userType"))) {//店長登錄
                jsonObject.put("storeid", aCache.getAsString("storeid"));
                url = Common.STORE_LOSS_REPORT_LIST;
            } else if ("1".equals(aCache.getAsString("userType"))) {//商戶登錄
                url = Common.LOSS_REPORT_LIST;
            }else{
                jsonObject.put("storeid", aCache.getAsString("storeid"));
                url = Common.STORE_LOSS_REPORT_LIST;
            }
            jsonObject.put("page", page);
            jsonObject.put("limit", 20);
            jsonObject.put("order_number", editRlManage.getText().toString().trim());
            jsonObject.put("start_time", startTimeRlManage.getText().toString().trim());
            jsonObject.put("end_time", endTimeRlManage.getText().toString().trim());
            Log.e(TAG, "getData: url==="+url );
            HttpUtils.post(context, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    listViewRlManage.onRefreshComplete();
                    reportLossListInfo = GsonUtils.JsonToBean(text, ReportLossListInfo.class);
                    Message message = new Message();
                    if (reportLossListInfo.getStatus() == 1) {
                        message.what = 1;
                    } else {
                        message.what = 2;
                    }
                    handler.sendMessage(message);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    listViewRlManage.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取報損詳情
     */
    private void getDetail(String id) {
        loadingDialog.show();
        String url = "";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", id);
            if ("2".equals(aCache.getAsString("userType"))) {//店長登錄
                jsonObject.put("storeid", aCache.getAsString("storeid"));
                url = Common.STORE_LOSS_INFO;
            } else if ("1".equals(aCache.getAsString("userType"))) {//商戶登錄
                url = Common.LOSS_INFO;
            }else{
                jsonObject.put("storeid", aCache.getAsString("storeid"));
                url = Common.STORE_LOSS_INFO;
            }
            HttpUtils.post(context, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    lossInfo = GsonUtils.JsonToBean(text, LossInfo.class);
                    Message msg = new Message();
                    if (lossInfo.getStatus() == 1) {
                        msg.what = 3;
                    } else {
                        msg.what = 4;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
